<template>
  <div class="toolbox">
    <el-dropdown @visible-change="handleVisible">
      <span class="el-dropdown-link" :class="{ active: isRound }">
        工具箱
        <el-icon class="el-icon--right" :class="{ active: isRound }">
          <arrow-down />
        </el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="handleAddLine">测量距离</el-dropdown-item>
          <el-dropdown-item @click="handleAddPolygon">测量面积</el-dropdown-item>
          <el-dropdown-item @click="claerEvent">关闭测量</el-dropdown-item>
          <el-dropdown-item @click="MapExportPng">导出图片</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { ArrowDown } from '@element-plus/icons-vue'
import { ref } from 'vue'
const { map } = defineProps({
  map: {
    type: Object,
    required: true,
  },
})
const isRound = ref(false)
const handleVisible = (e) => {
  isRound.value = e
}
let drawToolLayer, drawTool
function claerEvent() {
  if (drawToolLayer || drawTool) {
    map.removeLayer(drawToolLayer)
    drawToolLayer = null
    map.removeInteraction(drawTool)
    drawTool = null
  }
}
function handleAddLine() {
  claerEvent()
  AddLine()
}
function AddLine() {
  //实例化一个矢量图层Vector作为绘制层
  drawToolLayer = new ol.layer.Vector()
  const source = new ol.source.Vector({ wrapX: false })
  //添加绘制层数据源
  drawToolLayer.setSource(source)

  //实例化交互绘制类对象并添加到地图容器中
  drawTool = new ol.interaction.Draw({
    //绘制层数据源
    source: source,
    //几何图形类型
    type: 'LineString',
  })
  drawTool.on('drawend', onDrawEnd)
  //添加绘制控件
  map.addInteraction(drawTool)
  map.addLayer(drawToolLayer)
}
function handleAddPolygon() {
  claerEvent()
  AddPolygon()
}
function AddPolygon() {
  //实例化一个矢量图层Vector作为绘制层
  drawToolLayer = new ol.layer.Vector()
  const source = new ol.source.Vector({ wrapX: false })
  //添加绘制层数据源
  drawToolLayer.setSource(source)

  //实例化交互绘制类对象并添加到地图容器中
  drawTool = new ol.interaction.Draw({
    //绘制层数据源
    source: source,
    //几何图形类型
    type: 'Polygon',
  })
  drawTool.on('drawend', onDrawEnd)
  //添加绘制控件
  map.addInteraction(drawTool)
  map.addLayer(drawToolLayer)
}
function onDrawEnd(event) {
  const geoJsonFormat = new ol.format.GeoJSON()
  const geoJsonGeometryString = geoJsonFormat.writeGeometry(event.feature.getGeometry())
  const res = JSON.parse(geoJsonGeometryString)

  if (res.type == 'LineString') {
    const line = turf.lineString(res.coordinates)
    const length = turf.length(line)

    const pointline = res.coordinates[res.coordinates.length - 1]

    const pointFeature = new ol.Feature({
      geometry: new ol.geom.Point(pointline),
    })
    const textStyle = new ol.style.Style({
      text: new ol.style.Text({
        text: length.toFixed(2) + 'km',
        textAlign: 'center',
        fill: new ol.style.Fill({
          color: 'black',
        }),
        //  backgroundFill: new ol.style.Fill({
        //    color: '#5fadd9',
        //  }),
        padding: [5, 5, 5, 5],
        stroke: new ol.style.Stroke({ color: 'white', width: 2 }),
      }),
    })
    // // 创建带圆角和边框的背景样式   弃用
    // const backgroundStyle = new ol.style.Style({
    //     image: new ol.style.RegularShape({
    //     points: 64, //
    //     radius: 25, // 设置圆角半径
    //     radius1: 25, // 同上，用于更复杂的圆角设置
    //     radius2: 25, // 同上，用于更复杂的圆角设置
    //     angle: 0,
    //     fill: new ol.style.Fill({ color: '#5fadd9' }),
    //     stroke: new ol.style.Stroke({ color: 'white', width: 2 }),
    //     // size:[100,50], 没用
    //     anchor: [0.5, 0.5],
    //   }),
    // })

    // // 组合文本样式和背景样式
    // const combinedStyle = new ol.style.Style({
    //   text: textStyle.getText(),
    //   image: backgroundStyle.getImage(),
    // //   geometry: 'point', // 样式应用于点几何
    // })
    pointFeature.setStyle(textStyle)
    drawToolLayer.getSource().addFeature(pointFeature)
  } else if (res.type == 'Polygon') {
    const polygon = turf.polygon(res.coordinates)
    const area = turf.area(polygon)
    var center = turf.centerOfMass(polygon)

    const pointFeature = new ol.Feature({
      geometry: new ol.geom.Point(center.geometry.coordinates),
    })
    const textStyle = new ol.style.Style({
      text: new ol.style.Text({
        text: (area / 1000000).toFixed(2) + 'km²',
        textAlign: 'center',
        fill: new ol.style.Fill({
          color: 'black',
        }),
        //  backgroundFill: new ol.style.Fill({
        //    color: '#5fadd9',
        //  }),
        padding: [5, 5, 5, 5],
        stroke: new ol.style.Stroke({ color: 'white', width: 2 }),
      }),
    })
    pointFeature.setStyle(textStyle)
    drawToolLayer.getSource().addFeature(pointFeature)
  }
}
function MapExportPng() {
  map.once('postcompose', function (event) {
    var canvas = event.context.canvas

    canvas.toBlob(function (blob) {
      saveAs(blob, 'map.png')
    })
  })
  map.renderSync()
}
// function exportImg() {  //第三方插件失败
//   html2canvas(document.getElementById('map'),{useCORS: true,}).then(function (canvas) {
//     // 将 Canvas 转换为图片 URL
//     var imgData = canvas.toDataURL('image/png')
//     const link = document.createElement('a')
//     link.href = imgData
//     link.download = 'image.png' // 如果没有提供文件名，则默认为 'image.png'
//     // 模拟点击 <a> 标签，触发下载
//     document.body.appendChild(link)
//     link.click()
//     document.body.removeChild(link)
//   })
// }
// function exportImg() {    //失败,获取图片为空
//   map.once('rendercomplete', () => {
//     const mapCanvas = document.createElement('canvas')
//     const size = map.getSize()
//     mapCanvas.width = size[0]
//     mapCanvas.height = size[1]
//     const mapContext = mapCanvas.getContext('2d')
//     Array.prototype.forEach.call(
//       map.getViewport().querySelectorAll('.ol-layer canvas, canvas.ol-layer'),
//       function (canvas) {
//         if (canvas.width > 0) {
//           const opacity =
//             canvas.parentNode.style.opacity || canvas.style.opacity;
//           mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
//           let matrix;
//           const transform = canvas.style.transform;
//           if (transform) {
//             // Get the transform parameters from the style's transform matrix
//             matrix = transform
//               .match(/^matrix\(([^\(]*)\)$/)[1]
//               .split(',')
//               .map(Number);
//           } else {
//             matrix = [
//               parseFloat(canvas.style.width) / canvas.width,
//               0,
//               0,
//               parseFloat(canvas.style.height) / canvas.height,
//               0,
//               0,
//             ];
//           }
//           // Apply the transform to the export map context
//           CanvasRenderingContext2D.prototype.setTransform.apply(
//             mapContext,
//             matrix,
//           );
//           const backgroundColor = canvas.parentNode.style.backgroundColor;
//           if (backgroundColor) {
//             mapContext.fillStyle = backgroundColor;
//             mapContext.fillRect(0, 0, canvas.width, canvas.height);
//           }
//           mapContext.drawImage(canvas, 0, 0);
//         }
//       },
//     );
//     mapContext.globalAlpha = 1;
//     mapContext.setTransform(1, 0, 0, 1, 0, 0);

//     console.log(mapCanvas.toDataURL())
//     const link = document.createElement('a')
//     link.href = mapCanvas.toDataURL();
//     link.download = 'image.png' // 如果没有提供文件名，则默认为 'image.png'
//     // 模拟点击 <a> 标签，触发下载
//     document.body.appendChild(link)
//     link.click()
//     document.body.removeChild(link)
//   })
//   map.renderSync()
// }
</script>

<style lang="scss" scoped>
.toolbox {
  padding: 0px 15px;
  margin-bottom: 5px;
  cursor: pointer;
  .el-dropdown-link {
    border: none;
    outline: none;
    &.active {
      color: #409eff;
    }
  }
  .el-icon--right {
    transition: all 0.2s;
    transform: rotate(0deg);
    &.active {
      transform: rotate(180deg);
    }
  }
}
</style>
